import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: nn
 * Date: 2025-04-21
 * Time: 9:10
 */
public class BinaryTree {
    //创建二叉树
    static class TreeNode {
        public char val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(char val) {
            this.val = val;
        }
    }

    //以穷举的方式 创建一棵二叉树
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        E.right = H;
        return A;
    }

    //前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;//空树不需要遍历
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    //中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;//空树不需要遍历
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    //后序遍历
    public void postOrder(TreeNode root) {
        if (root == null) {
            return;////空树不需要遍历
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    // 获取树中节点的个数
    public static int nodeSiz;//获取树中节点的个数

    public void size(TreeNode root) {
        if (root == null) {
            return;//空树是不需要遍历的
        }
        nodeSiz++;
        size(root.left);
        size(root.right);
    }

    public int siz2(TreeNode root) {//子问题思路
        if (root == null) {
            return 0;
        }
        return siz2(root.left) + siz2(root.right) + 1;
    }

    //获取叶子节点的个数；叶子节点：度为0的节点
    public int leafSize;

    public void getLeafNodeCount(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
    }

    public int getLeafNodeCount2(TreeNode root) {//子问题思路
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    // root的第k层有多少个节点
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        return getKLevelNodeCount(root.left, k - 1) + getKLevelNodeCount(root.right, k - 1);
    }

    //O(N)
    //https://leetcode.cn/problems/maximum-depth-of-binary-tree/submissions/
    // 获取二叉树的高度
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);

        return Math.max(leftHeight, rightHeight) + 1;
    }

    public int getHeight2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight2(root.left);
        int rightHeight = getHeight2(root.right);

        return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
    }

    public int getHeight3(TreeNode root) {
        if (root == null) {
            return 0;
        }

        return (getHeight3(root.left) > getHeight3(root.right)
                ? getHeight3(root.left) : getHeight3(root.right)) + 1;
    }

    //检测值为value的元素是否存在
    public TreeNode find(TreeNode root, int val) {
        if (root == null) return null;
        if (root.val == val) return root;

        TreeNode leftVal = find(root.left, val);
        if (leftVal != null) {
            return leftVal;
        }
        TreeNode rightVal = find(root.right, val);
        if (rightVal != null) {
            return rightVal;
        }
        return null; //说明左右子树都没找到
    }

    //1. 检查两颗树是否相同。OJ链接
    //时间复杂度:O(min(M,N)),一不相同就停下来了
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p != null && q == null || p == null && q != null) {
            //结构不一样
            return false;
        }
        //上述If语句没有进来 那么说明  要么两个都是空 要么两个都不是空
        if (p == null && q == null) {
            return true;
        }
        //两个都不为空
        if (p.val != q.val) {
            return false;
        }
        //上述代码完成 走到这里 说明p != null && q != null && 根节点值一样
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    //2. 另一颗树的子树。OJ链接
    //m  n  -> O(m*n) ->时间复杂度
    // root这棵树的每个节点 都要和subRoot判断是否相同
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) {//防止空指针异常
            return false;
        }
        if (isSameTree(root, subRoot)) {
            return true;
        }
        if (isSubtree(root.left, subRoot)) {
            return true;
        }
        if (isSubtree(root.right, subRoot)) {
            return true;
        }
        return false;
    }

    //3. 翻转二叉树。Oj链接
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (root.left == null && root.right == null) {
            return root;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    //4. 判断一颗二叉树是否是平衡二叉树。OJ链接
    //每一个节点判断每个节点左树和右树的高度差是不是小于2
    //时间复杂度：O(N^2)  ->
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftH = getHeight(root.left);
        int rightH = getHeight(root.right);
        if (Math.abs(leftH - rightH) < 2 && isBalanced(root.left) && isBalanced(root.right)) {
            return true;
        }
        return false;
    }

    public boolean isBalanced2(TreeNode root) {
        if (root == null) {
            return true;
        }
        return getHeight22(root) >= 0;
    }

    public int getHeight22(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight22(root.left);
        if (leftHeight < 0) {
            return -1;
        }
        int rightHeight = getHeight22(root.right);
        //刚刚已经约定 不平衡会返回负数
        if (leftHeight >= 0 && rightHeight >= 0
                && Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            //不平衡
            return -1;
        }
    }

    //5. 对称二叉树。OJ链接
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
        //1.结构上的判断
        if(leftTree == null && rightTree != null ||
                leftTree != null && rightTree == null) {
            return false;
        }
        if(leftTree == null && rightTree == null ) {
            return true;
        }
        //2. 值
        if(leftTree.val != rightTree.val) {
            return false;
        }
        //3. 都不为空 且当前节点值一样了，继续判断左和右
        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,rightTree.left);
    }

    //层序遍历 用队列来实现（不使用递归）
    public void levelOrder(TreeNode root){
        if(root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//是将根节点添加到队列中
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();//从队列中取出并移除队首元素
            System.out.println(cur.val + " ");
            if (cur.left != null){
                queue.offer(cur.left);
            }
            if (cur.right != null){
                queue.offer(cur.right);
            }
        }
    }

    //把每一层 放到一个List里面
    public List<List<Character>> levelorder2(TreeNode root){
        List<List<Character>> retLsit = new ArrayList<>();
        if(root == null) {
            return retLsit;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//是将根节点添加到队列中
        while(!queue.isEmpty()){
            //那当前队列的节点个数来看的
            int size = queue.size();
            List<Character> list = new ArrayList<>();
            while(size != 0){
                TreeNode cur = queue.poll();//从队列中取出并移除队首元素
                list.add(cur.val);
                size--;
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            retLsit.add(list);
        }
        return retLsit;
    }
    /*判断一棵树是不是完全二叉树*/
    public boolean isCompleTree(TreeNode root){
        if(root == null) return true;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);//将元素 root 添加到队列的尾部（队尾）。
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur != null){
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;//结束之后 遍历列表剩下的所有元素 是不是都是null
            }
        }
        //遍历队列剩下的所有元素 是不是都是null
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur != null){
                return false;
            }
        }
        return true;
    }

    //8.给定一个二叉树，找到该树中两个指定节点的最近公共祖先。OJ链接
    public TreeNode lowestCommonAncestor(TreeNode root,
                                         TreeNode p, TreeNode q) {
        if(root == null){
            return root;
        }
        if(root == p || root ==q){
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left , p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left != null && right != null){
            return root;
        }else if(left != null ){
            return left;
        }else {
            return right;
        }
    }
    /*
    * 方法二：
    * @param root 根节点
    * @param node 要查找指定的节点
    * @param stack 存储路径
    * @return 返回值
    * */
    public boolean getPath(TreeNode root, TreeNode node,
                           Stack<TreeNode> stack) {
        if (root == null){
            return false;
        }
        stack.push(root);
        if (root == node){
            return true;
        }
        boolean flgLeft = getPath(root.left,node,stack);
        if (flgLeft){
            return true;
        }
        boolean flgRight = getPath(root.right,node,stack);
        if (flgRight){
            return true;
        }
        stack.pop();
        return false;
    }



    public TreeNode lowestCommonAncestor2(TreeNode root,
                                         TreeNode p, TreeNode q) {
        if (root == null){
            return root;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();

        getPath(root,p,stack1);
        getPath(root,q,stack2);

        int size1 =stack1.size();
        int size2 =stack2.size();

        if(size1 > size2){
            int size = size1 - size2;
            while(size != 0 ){
                stack1.pop();
                size--;
            }
        }
        if(size1 < size2){
            int size = size2 - size1;
            while(size != 0 ){
                stack2.pop();
                size--;
            }
        }

        while (!stack1.isEmpty() && !stack2.isEmpty()){
            if (stack1.peek().val == stack2.peek().val){
                return stack1.pop();
            }else {
                stack1.pop();
                stack2.pop();
            }
        }
        return null;
    }

//    9. 根据一棵树的前序遍历与中序遍历构造二叉树。 OJ链接


//    10. 根据一棵树的中序遍历与后序遍历构造二叉树（[课堂不讲解，课后完成作业]）。OJ链接
}

